const db = require('../db/index')
const bcrypt = require('bcryptjs')

// 获取用户资料
exports.getUserInfo = (req, res) => {
  const sql = `select a.uid,a.account ,b.tel ,b.site ,b.remarks from user a ,address b where a.uid = b.uid and a.uid = ? `
  // const sql = `select * from user where uid = ? `
  db.query(sql, req.query.uid, (err, results) => {
    if (err) return res.cc(err)
    if (results.length < 0) return res.cc('获取用户资料失败！')
    res.send({
      status: 0,
      message: '获取用户资料成功！',
      data: results
    })
  })
}

// 更新用户资料
exports.updateUserInfo = (req, res) => {
  // 定义根据 id 查询用户数据的 SQL 语句
  const sql = `select * from user where uid = ?`

  // 执行 SQL 语句查询用户是否存在
  db.query(sql, req.body.uid, (err, results) => {
    // 执行 SQL 语句失败
    if (err) return res.cc(err)

    // 检查指定 id 的用户是否存在
    if (results.length !== 1) return res.cc('用户不存在！')

    // 判断提交的旧密码是否正确
    const compareResult = bcrypt.compareSync(req.body.oldPwd, results[0].password)
    if (!compareResult) return res.cc('原密码错误！')

    // 定义更新用户密码的 SQL 语句
    const sql = `UPDATE user set account = ?,phone = ?,password =? where uid = ?`

    // 对新密码进行 bcrypt 加密处理
    const newPwd = bcrypt.hashSync(req.body.newPwd, 10)

    // 执行 SQL 语句，根据 id 更新用户的密码
    db.query(sql, [req.body.account, req.body.phone, newPwd, req.body.uid], (err, results) => {
      console.log(req.body)
      // SQL 语句执行失败
      if (err) return res.cc(err)

      // SQL 语句执行成功，但是影响行数不等于 1
      if (results.affectedRows !== 1) return res.cc('更新密码失败！')

      // 更新密码成功
      res.cc('更新密码成功！', 0)
    })
  })
}

// 获取用户下单地址
exports.getUserAddress = (req, res) => {
  const sql = `select * from address where uid = ? `
  db.query(sql, req.query.uid, (err, results) => {
    if (err) return res.cc(err)
    if (results.length < 0) return res.cc('获取用户下单地址失败！')
    res.send({
      status: 0,
      message: '获取用户下单地址成功！',
      data: results
    })
  })
}

// 修改用户下单地址
exports.updteAddress = (req, res) => {
  const sql = `update address set name = ?,tel = ?, site = ? where uid = ? `
  db.query(sql, [req.body.name, req.body.tel, req.body.site, req.body.uid], (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) return res.cc('修改地址失败！')
    res.send({
      status: 0,
      message: '修改地址成功！',
      data: results
    })
  })
}

// 添加用户下单地址
exports.insertAddress = (req, res) => {
  const sql = `insert into address set name = ?, tel = ?, site = ?, uid = ? ,remarks = ?`
  db.query(sql, [req.body.name, req.body.tel, req.body.site, req.body.uid, req.body.remarks], (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) return res.cc('添加地址失败！')
    res.send({
      status: 0,
      message: '添加地址成功！',
      data: results
    })
  })
}
